<template>
  <div>
    <card :_Title="i18nText('address.shippingAddress', '收货地址')" />
    <div class="add-box">
      <Form :model="formData" ref="form" label-position="right" :label-width="160" :rules="ruleInline">
        <FormItem :label="i18nText('address.country', '国家')" prop="countryId">
          <Select v-model="formData.countryId" style="width:200px" filterable @on-change="countryChange">
            <Option v-for="item in countries" :value="item.id" :key="item.id">{{ item.name_en }}</Option>
          </Select>
        </FormItem>
        <FormItem :label="i18nText('address.consignee', '收货人')" prop="name">
          <i-input v-model="formData.name" :placeholder="i18nText('address.pleaseEnterTheConsigneesName', '请输入收货人姓名')" style="width: 600px"></i-input>
        </FormItem>
<!--        <FormItem label="收件地区" prop="address">
          <span>{{ formData.address || '暂无地址' }}</span>

          <Button type="default" style="margin-left: 10px;" size="small" @click="$refs.map.open()">选择</Button>
        </FormItem>-->
        <FormItem :label="i18nText('address.addressLine1', '详细地址')" prop="detail">
          <i-input v-model="formData.detail" :placeholder="i18nText('address.pleaseEnterTheDetailedAddress', '请输入详细地址')" style="width: 600px"></i-input>
        </FormItem>
        <Row>
          <Col span="10">
            <FormItem :label="i18nText('address.cityTown', '城市')" prop="cityName">
              <i-input v-model="formData.cityName" :placeholder="i18nText('address.pleaseEnterTheCityTown', '请输入城市')"></i-input>
            </FormItem>
          </Col>
          <Col span="10">
            <FormItem :label="i18nText('address.provinceRegionState', '地区')" prop="region">
              <Select v-if="regiones && regiones.length > 0" v-model="formData.region" filterable>
                <Option v-for="item in regiones" :value="item.name_en" :key="item.id">{{ item.name_en }}</Option>
              </Select>
              <i-input v-else v-model="formData.region" :placeholder="i18nText('address.pleaseEnterTheRegion', '请输入地区')" ></i-input>
            </FormItem>
          </Col>
        </Row>
        <FormItem :label="i18nText('address.postalZIPCode', '邮政编码')" prop="postalCode">
          <i-input v-model="formData.postalCode" :placeholder="i18nText('address.pleaseEnterThePostalZipCode', '请输入邮政编码')" style="width: 600px"></i-input>
        </FormItem>
        <FormItem :label="i18nText('personInfo.phoneNumber', '手机号码')" prop="mobile">
          <i-input v-model="formData.mobile" :placeholder="i18nText('personInfo.pleaseEnterPhoneNumber', '请输入收件人手机号')" style="width: 600px"></i-input>
        </FormItem>
        <FormItem :label="i18nText('address.note', '地址别名')">
          <i-input v-model="formData.alias" length :maxlength="30" :placeholder="i18nText('address.markThisAddress', '请输入地址别名，例如公司')" style="width: 600px">
          </i-input>
        </FormItem>
        <FormItem :label="i18nText('address.defaultShippingAddress', '默认地址')">
          <i-switch v-model="formData.isDefault" />
        </FormItem>
      </Form>
    </div>
    <div class="mt_20">
      <Button type="primary" class="mr_10" :loading="loading" @click="save">{{ i18nText('common.save', '保存收货地址') }}</Button>
      <Button @click="$router.back()">{{ i18nText('common.return', '返回') }}</Button>
    </div>

    <multipleMap  ref="map" @callback="getAddress" />
  </div>
</template>

<script>
import card from "@/components/card";

import multipleMap from "@/components/map/multiple-map";
import * as RegExp from "@/plugins/RegExp.js";
import options from "@/store/global-address";
import { i18nText } from '@/utils/i18n'

import {
  newMemberAddress,
  editMemberAddress,
  getAddrDetail,
} from "@/api/address";
export default {
  name: "AddAddress",
  data() {
    return {
      formData: {
        // 添加地址表单
        isDefault: false,
        countryId: '',
        region: '',
        cityName: '',
        postalCode: '',
      },
      ruleInline: {
        // 验证规则
        name: [{ required: true, message: i18nText('personInfo.pleaseEnterName', '请输入姓名'), trigger: "blur" }],
        address: [{ required: true, message: i18nText('address.pleaseEnterShippingAddress', '请输入地址'), trigger: "change" }],
        countryId: [{ required: true, message: i18nText('address.pleaseSelectACountry', '请选择国家'), trigger: "change" }],
        region: [{ required: true, message: i18nText('address.pleaseEnterTheRegion', '请输入地区'), trigger: "change" }],
        cityName: [{ required: true, message: i18nText('address.pleaseEnterTheCityTown', '请输入城市'), trigger: "change" }],
        postalCode: [{ required: true, message: i18nText('address.pleaseEnterThePostalZipCode', '请输入邮政编码'), trigger: "change" }],
        detail: [
          { required: true, message: i18nText('address.pleaseEnterTheDetailedAddress', '请输入详细地址'), trigger: "blur" },
        ],
        mobile: [
          { required: true, message: i18nText('personInfo.pleaseEnterPhoneNumber', '请输入手机号码') },
        ],
      },
      loading: false, // 加载状态
      mapMsg: {}, // 地图信息
      countries: [], // 国家
      regionMap: new Map, // 地区
      regiones: [], // 地区
    };
  },
  created() {
    // 国家
    let countries = []
    // 地区
    let regionMap = new Map()
    options.forEach(continent => {
      continent.childrens.forEach(country => {
        countries.push(country)
        regionMap.set(country.id, country.childrens)
      })
    })
    countries = countries.sort((a, b) => a.name_en.localeCompare(b.name_en))
    this.countries = countries
    this.regionMap = regionMap
  },
  methods: {
    save() {
      // 保存地址
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = JSON.parse(JSON.stringify(this.formData));
          // params.consigneeAddressPath = params.address.replace(/\s/g, ",");
          // delete params.address;
          // 筛选国家
          const countryName = this.countries.filter(item => item.id === this.formData.countryId)[0].name_en
          // 拼接地址，由小到大
          params.consigneeAddressPath = this.formData.cityName + ',' +  this.formData.region + ',' +  countryName
          this.loading = true;
          if (this.$route.query.id) {
            editMemberAddress(params)
              .then((res) => {
                if (res.success) {
                  this.loading = false;
                  this.$router.push("/home/MyAddress");
                }
              })
              .catch(() => {
                this.loading = false;
              });
          } else {
            newMemberAddress(params)
              .then((res) => {
                if (res.success) {
                  this.loading = false;
                  this.$router.push("/home/MyAddress");
                }
              })
              .catch(() => {
                this.loading = false;
              });
          }
        }
      });
    },
    getAddrById(id) {
      // 获取地址详情
      getAddrDetail(id).then((res) => {
        if (res.success) {
          const data = res.result;
          this.formData.countryId = data.countryId
          this.countryChange(data.countryId)
          // data.address = res.result.consigneeAddressPath.replace(/,/g, " ");
          this.formData = data;
        }
      });
    },
    getAddress(val) {
      // 获取地图选择信息
      if(val.type === 'select'){
        const paths = val.data.map(item => item.name).join(',')
        const ids = val.data.map(item => item.id).join(',')
        this.$set(this.formData,'address',paths)
        this.$set(this.formData,'consigneeAddressIdPath',ids)
        const coord = val.data[val.data.length - 1].center.split(',')
        this.formData.lat = coord[1]
        this.formData.lon = coord[0]
      }else{
        this.$set(this.formData, "address", val.data.addr);
        this.$set(this.formData, "consigneeAddressIdPath", val.data.addrId);
        this.$set(this.formData, "detail", val.data.address);
        this.formData.lat = val.data.position.lat;
        this.formData.lon = val.data.position.lng;
      }
    },
    /**
     * 国家选择监听
     * @param countryId
     */
    countryChange(countryId) {
      this.regiones = this.regionMap.get(countryId)
    }
  },
  mounted() {
    const id = this.$route.query.id;
    if (id) this.getAddrById(id);
  },
  components: {
    card,
    multipleMap
  },
};
</script>

<style scoped lang="scss">
.add-box {
  margin: 40px 0;
}
</style>
